import ajax from '../js/ajax'
import '../css/index.css'

let t = document.getElementById('t')
let sure = document.getElementById('sure')
let cancel = document.getElementById('cancel')
let block = document.getElementById('block')
let news = document.getElementById('newPassword')
let old = document.getElementById('oldPassword')


list()
async function list() {
    await ajax('get', '/api/list').then(function (result) {
        b(result)
    }).catch(function (err) {
        alert(err)
        location.href = 'login.html'
    })
}



// setInterval(function list() {

//     let xhr = new XMLHttpRequest
//     xhr.onreadystatechange = function () {
//         if (xhr.readyState == 4) {
//             if (xhr.status == 200) {
//                 let a = JSON.parse(xhr.response)
//                 b(a)
//             } else {
//                 alert(xhr.status + '登录超时请重新登录')
//                 location.href = 'loginn.html'

//             }
//         }

//     }

//     xhr.open('get', '/api/list', true)
//     xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token'))
//     xhr.send()
// }, 100
// )




function b(data) {
    t.innerHTML = ""
    t.innerHTML = `
    <tr>
        <th>序列号</th>
        <th>用户名</th>
        <th>密码</th>
        <th>创建时间</th>
        <th>更新时间</th>
        <th>操作</th>
    </tr>`
    console.log(data);
    for (const item of data) {
        console.log(item);
        let tr = document.createElement('tr')
        for (const q in item) {
            let td = document.createElement('td')
            td.innerText = item[q]
            tr.append(td)
        }
        let td = document.createElement('td')
        td.innerHTML = ` <span  id=${item.id}>修改</span>   <span id=${item.id} name='delete'>删除</span>`
        tr.append(td)
        t.append(tr)

    }

}


t.onclick = async function (e) {
    let ee = e

    if (e.target.id != '' && e.target.innerText == '删除') {
        if (confirm('确定删除吗')) {
            await ajax('post', '/api/delete', { id: e.target.id }).then(function (result) {
                list()
            })
        }

    }
    if (e.target.id != '' && e.target.innerText == '修改') {
 
        e.target.parentElement.parentElement.style.backgroundColor = '#ccc'
        block.style.display = "block"
        sure.onclick = function () {
            ajax('post', '/api/updata', { old: old.value, news: news.value, id: e.target.id }).then(function (result) {
                if (result.flag) {
                    list();
                  
                    block.style.display = "none"
                    e.target.parentElement.parentElement.style.backgroundColor = '#ccc'

                } else {
                    alert(result.msg)
                }

            })
        }
        cancel.onclick = function () {
    
            ee.target.parentElement.parentElement.style.backgroundColor = ''
            block.style.display = "none"


        }
    }

}
